package net.thetabx.ftdba.activities;

import net.thetabx.ftdba.GlobalData;
import net.thetabx.ftdba.R;
import net.thetabx.ftdba.RStatus;
import net.thetabx.ftdba.http.HttpData;
import net.thetabx.ftdba.http.HttpManager;
import net.thetabx.ftdba.objects.Torrent;
import net.thetabx.ftdba.objects.Torrents;
import net.thetabx.ftdba.utils.TextEncoder;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class TorrentsListActivity extends Activity {
	private static final String TAG = "TorrentsListActivity";
	private Spinner spnTorrentType;
	private ListView listTorrentData;
	private EditText edtTorrentSearch;
	
	private HttpManager http;
	
	private Integer[] imageIconDatabase = { R.drawable.torrent_all, 
			R.drawable.torrent_dvdrip, R.drawable.torrent_dvdrip_vostfr, R.drawable.torrent_dvdr, R.drawable.torrent_hd_720p, R.drawable.torrent_hd_1080p, R.drawable.torrent_full_bluray, R.drawable.torrent_3d, 
			R.drawable.torrent_tv_vf, R.drawable.torrent_tv_hd_vf, R.drawable.torrent_tv_vostfr, R.drawable.torrent_tv_hd_vostfr, R.drawable.torrent_tv_vo, R.drawable.torrent_dvdr_tv, R.drawable.torrent_tv_pack, 
			R.drawable.torrent_jeux, R.drawable.torrent_application, 
			R.drawable.torrent_cam_ts_screener, R.drawable.torrent_dvd_screener, R.drawable.torrent_r5, R.drawable.torrent_ebook, R.drawable.torrent_inclassable, R.drawable.torrent_musiques, 
			R.drawable.torrent_documentaire, R.drawable.torrent_sport, R.drawable.torrent_spectacle, R.drawable.torrent_dessins_animes, R.drawable.torrent_television};
	private String[] imageNameDatabase = { "0", 
			"4", "5", "7", "22", "23", "29", "31",
			"12", "36", "13", "37", "39", "42", "43", 
			"14", "15", 
			"1", "2", "6", "17", "19", "16", 
			"21", "30", "10", "20", "44" };
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.torrents_list);
        
        spnTorrentType = (Spinner)findViewById(R.id.spnTorrentType);
    	listTorrentData = (ListView)findViewById(R.id.listTorrentData);
    	edtTorrentSearch = (EditText)findViewById(R.id.edtTorrentSearch);
    	http = GlobalData.getHttpManager();
    	
    	spnTorrentType.setAdapter(new TorrentSpinnerAdapter(TorrentsListActivity.this, R.layout.torrents_spinner_row, imageNameDatabase));
    	spnTorrentType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				if(arg1 != null)
					new TorrentsListFiller().execute((String)arg1.getTag());
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
    	});
    	
    	edtTorrentSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if(v != edtTorrentSearch || edtTorrentSearch.getText().toString().equals(""))
					return false;
				//if(actionId == EditorInfo.IME_NULL || actionId == EditorInfo.IME_ACTION_DONE) {
					new TorrentsListFiller().execute((String)spnTorrentType.getSelectedView().getTag(), edtTorrentSearch.getText().toString());
					InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(edtTorrentSearch.getWindowToken(), 0);
					return false;
				//}
				//return false;
			}
		});
	}
	
	public class TorrentsListFiller extends AsyncTask<String, Boolean, RStatus> {
		Torrents torrentList;
		
		@Override
		protected RStatus doInBackground(String... params) {
			if(http == null)
				return RStatus.NO_HTTP;
			
			Log.v(TAG, "Getting torrents list");
			HttpData data = http.send("/?section=TORRENTS&ajax=1" + (params[0] != "0" ? "&parent_cat_id=" + params[0] : "") + (params.length > 1 && params[1] != null ? "&search=Rechercher&exact=1&name=" + TextEncoder.EncodeText(params[1]) : ""));
			if(data.getStatus() != RStatus.ENDED)
				return data.getStatus();
			
			// Parse data
			torrentList = new Torrents(data.getContentSb().toString());
			return RStatus.ENDED;
		}
		
		@Override
		protected void onPostExecute(final RStatus status) {
			if(status == RStatus.ENDED) {
				listTorrentData.post(new Runnable() {
					public void run() {
						TorrentAdapter tAdapter = new TorrentAdapter(GlobalData.getContext(), torrentList);
	            		listTorrentData.setAdapter(tAdapter);
	            	}
	            });
			}
			else
        		Log.d(TAG, "Can't get torrents list : " + status.name());
		}
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
    	menu.findItem(R.id.menu_torrents).setVisible(false);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
	        case R.id.menu_userstat: {
	        	finish();
	            return true;
	        }
            case R.id.menu_shoutbox: {
            	finish();
            	startActivity(new Intent(this, ShoutboxActivity.class));
        		return true;
            }
            case R.id.menu_userlist: {
            	finish();
            	startActivity(new Intent(this, UserlistActivity.class));
        		return true;
            }
            case R.id.menu_options: {
            	finish();
            	startActivity(new Intent(this, OptionsActivity.class));
        		return true;
            }
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    public class TorrentSpinnerAdapter extends ArrayAdapter<String> {
    	 
        public TorrentSpinnerAdapter(Context context, int textViewResourceId, String[] objects) {
            super(context, textViewResourceId, objects);
        }
 
        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }
 
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }
 
        public View getCustomView(int position, View convertView, ViewGroup parent) {
 
            LayoutInflater inflater=getLayoutInflater();
            View row = inflater.inflate(R.layout.torrents_spinner_row, parent, false);
            row.setTag(imageNameDatabase[position]);
            
            ImageView icon=(ImageView)row.findViewById(R.id.spinner_torrent_row_img);
            icon.setImageResource(imageIconDatabase[position]);
 
            return row;
        }
    }

    public class TorrentAdapter extends BaseAdapter {

    	private Torrents torrents;
    	private Context mContext;
    	private LayoutInflater mInflater;
    	
    	public TorrentAdapter(Context context, Torrents torrents) {
    		this.mContext = context;
    		this.torrents = torrents;
    		this.mInflater = LayoutInflater.from(mContext);
    	}
    	
    	public int getCount() {
    		return torrents.size();
    	}

    	public Object getItem(int position) {
    		return torrents.get(position);
    	}

    	public long getItemId(int position) {
    		return position;
    	}

    	public View getView(int position, View convertView, ViewGroup parent) {
    		View layoutItem;
    			
    		if (convertView == null)
    			layoutItem = (View) mInflater.inflate(R.layout.torrents_list_row, parent, false);
    		else
    			layoutItem = (View) convertView;
    		
    		TextView textTorrentName = (TextView)layoutItem.findViewById(R.id.torrent_name);
    		final Torrent t = torrents.get(position);
    		textTorrentName.setText(t.getTitle());

    		layoutItem.setOnTouchListener(new View.OnTouchListener() {
				public boolean onTouch(View v, MotionEvent event) {
					Log.d(TAG, "onTouch");
					return false;
				}
			});
    		layoutItem.setOnKeyListener(new View.OnKeyListener() {
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					Log.d(TAG, "onKey");
					return false;
				}
			});
    		layoutItem.setOnClickListener(new View.OnClickListener() {
    			public void onClick(View v) {
    				Log.d(TAG, "onClick");
    				Intent i = new Intent(TorrentsListActivity.this, TorrentDetailsActivity.class);
    				i.putExtra("torrent_id", t.getId());
    				startActivity(i);
    			}
    		});
    		
    		
    		
    		return layoutItem;
    	}
    }
}
